from fastapi import APIRouter, Depends, Request, Header
from sqlalchemy.orm import Session
from typing import Annotated
from app.dependencies.db import get_db
from ...extensions.dependencies import get_query_token2
from app.services import get_merc_key
from ...schemas.demo import User, DemoPostBase
from ...services import demo as demo_svc
from ...utils import sign_util, biz_sign_util, common_util, sm4_util, bz_pay_util
from app.common.exceptions import GenericException
from app.common.enums import ErrTypes
from app.schemas.demo import SignParamBody, VerifyParamBody

import logging
logger = logging.getLogger(__name__)

router = APIRouter()
#router = APIRouter(dependencies=[Depends(get_query_token2)],)

@router.post("/gen_params", tags=["demo"])
async def gen_params(req: Request, reqBody: SignParamBody):
    print('>> gen_params')
    resp_data = {}
    try:
        #body = await req.body()
        #print('body: %s' % body)
        secret_key = reqBody.secret_key
        private_key = reqBody.private_key
        public_key = reqBody.public_key
        params = reqBody.params
        #merc_key_obj = get_merc_key(db, x_xpay_client_id)
        #secret_key = merc_key_obj.secret_key
        pay_util = bz_pay_util.BzPayUtil(secret_key=secret_key, 
                                        pri_key=private_key,
                                        pub_key=public_key)
        if isinstance(params, str):
            resp_data['signature'] = pay_util.sign_str_with_sm2(params)
            resp_data['params'] = pay_util.encrypt_str_with_sm4(params)
        elif isinstance(params, dict):
            resp_data['signature'] = pay_util.sign_with_sm2(params)
            resp_data['params'] = pay_util.encrypt_with_sm4(params)
        else:
            raise GenericException(error_type=ErrTypes.param_error)
        return resp_data
    except Exception as err:
        logger.error('加密/加签错误, Error: %s' % err)
        raise GenericException(error_type=ErrTypes.encryption_error)

@router.post("/verify_params", tags=["demo"])
async def verify_params(req: Request, reqBody: VerifyParamBody):
    print('>> verify_params')
    body = await req.body()
    resp_data = {}
    try:
        secret_key = reqBody.secret_key
        public_key = reqBody.public_key
        params = reqBody.params
        signature = reqBody.signature
        print('params: %s' % params)
        print('signature: %s' % signature)
        pay_util = bz_pay_util.BzPayUtil(secret_key=secret_key, 
                                        pub_key=public_key)
        if isinstance(params, str):
            resp_data['params'] = pay_util.decrypt_with_sm4(params)
            resp_data['verify_result'] = pay_util.verify_with_sm2(resp_data['params'], signature)
        elif isinstance(params, dict):
            #resp_data['signature'] = pay_util.sign_with_sm2(params)
            resp_data['verify_result'] = pay_util.verify_with_sm2(params, signature)
        else:
            raise GenericException(error_type=ErrTypes.param_error)
        return resp_data
    except Exception as err:
        logger.error('解密/验签错误, Error: %s' % err)
        raise GenericException(error_type=ErrTypes.decryption_error)